package com.pi.uc.facade;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import com.pi.base.dto.result.respcode.user.UcResp;
import com.pi.base.exception.ServiceException;
import com.pi.uc.dao.entity.UcUserEntity;
import com.pi.uc.service.UcUserService;
import com.pi.uc.vo.PrimeUserVo;
import com.pi.uc.vo.UserExtendInfoVo;
import com.pi.uc.vo.UserInfoVo;

@Service
public class UserTransFacade {
  
  @Autowired
  private UcUserService userService;
  public UserInfoVo transUserEntityToBasic(UcUserEntity entity){
    if(null == entity){
      throw new ServiceException(
          UcResp.RESP_USER_NOT_FOUND.getTag(), 
          UcResp.RESP_USER_NOT_FOUND.getErrorCode());
    }
    UserInfoVo vo = new UserInfoVo();
    transBasic(entity, vo);
    return vo;
  }
  
  public UserExtendInfoVo transUserEntityToDetail(UcUserEntity entity){
    checkEntity(entity);
    UserExtendInfoVo vo = new UserExtendInfoVo();
    transBasic(entity, vo);
    return vo;
  }
  
  public List<PrimeUserVo> transUsersToPrime(List<Long> userIds){
    List<PrimeUserVo> userList = new ArrayList<PrimeUserVo>();
    if(CollectionUtils.isEmpty(userIds)){
      return userList;
    }
    List<UcUserEntity> userEntitys = userService.queryUserByIds(userIds);
    if(CollectionUtils.isEmpty(userEntitys)){
      return userList;
    }
    for(UcUserEntity entity:userEntitys){
      PrimeUserVo vo = new PrimeUserVo();
      transPrime(entity, vo);
      userList.add(vo);
    }
    return userList;
  }
  
  private <T extends UserInfoVo>T transBasic(UcUserEntity entity, T vo){
    vo.setAge(entity.getAge());
    vo.setEducation(entity.getEducation());
    vo.setMobile(entity.getMobile());
    vo.setSex(entity.getSex());
    transPrime(entity, vo);
    return vo;
  }
  
  private <T extends PrimeUserVo>T transPrime(UcUserEntity entity, T vo){
    vo.setAvatar(entity.getAvatar());
    vo.setName(entity.getName());
    vo.setUserId(entity.getId().toString());
    return vo;
  }
  
  private void checkEntity(UcUserEntity entity){
    if(null == entity){
      throw new ServiceException(
          UcResp.RESP_USER_NOT_FOUND.getTag(), 
          UcResp.RESP_USER_NOT_FOUND.getErrorCode());
    }
  }
}
